using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.IO;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using CommunityToolkit.Mvvm.DependencyInjection;
using AvaloniaUiKit.SampleApp.Extensions;
using HanumanInstitute.MvvmDialogs;
using HanumanInstitute.MvvmDialogs.Avalonia;
using HanumanInstitute.MvvmDialogs.FrameworkDialogs;

namespace AvaloniaUiKit.SampleApp.ViewModels.Pages
{
    public partial class MvvmDialogsPageViewModel : PageViewModelBase
    {
        private readonly IDialogService _dialogService;

        public MvvmDialogsPageViewModel()
            : base("MvvmDialogs", "Examples of using MvvmDialogs with AvaloniaUiKit")
        {
            // Get the dialog service from the application resources
            if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop &&
                desktop.MainWindow is Window mainWindow &&
                mainWindow.Resources.TryGetResource("DialogService", null, out var dialogService) &&
                dialogService is IDialogService service)
            {
                _dialogService = service;
            }
            else
            {
                // Fallback to default dialog service if not found in resources
                _dialogService = new DialogService();
            }
        }

        [RelayCommand]
        private async Task ShowMessageBox()
        {
            await _dialogService.ShowMessageBoxAsync(
                "This is a simple message box",
                "Message Box Example");
        }

        [RelayCommand]
        private async Task ShowConfirmation()
        {
            var result = await _dialogService.ShowMessageBoxAsync(
                "Are you sure you want to continue?",
                "Confirmation",
                MessageBoxButton.YesNo,
                MessageBoxImage.Information);

            if (result == true)
            {
                await _dialogService.ShowMessageBoxAsync(

                    "You clicked Yes!",
                    "Result");
            }
        }

        [RelayCommand]
        private async Task ShowOpenFileDialog()
        {
            var settings = new OpenFileDialogSettings
            {
                Title = "Select a file",
                Filters = new List<FileFilter>()
                {
                    new(
                        "Text Documents",
                        new[]
                        {
                            "txt", "md"
                        }),
                    new(
                        "Binaries",
                        new[]
                        {
                            ".exe", ".dll"
                        }),
                    new("All Files", "*")
                },
                AllowMultiple = false
            };

            var result = await _dialogService.ShowOpenFileDialogAsync(settings);
            if (result != null)
            {
                await _dialogService.ShowMessageBoxAsync(
                    this,
                    $"Selected file: {result}",
                    "File Selected");
            }
        }

        [RelayCommand]
        private async Task ShowCustomDialog()
        {
            try
            {
                var dialogViewModel = new CustomDialogViewModel();
                var result = await _dialogService.ShowDialogAsync<bool>(dialogViewModel);
                
                await _dialogService.ShowMessageBoxAsync(
                    $"Dialog result: {result}",
                    "Dialog Closed");
            }
            catch (Exception ex)
            {
                await _dialogService.ShowMessageBoxAsync(
                    $"Error showing dialog: {ex.Message}",
                    "Error",
                    MessageBoxButton.Ok,
                    MessageBoxImage.Error);
            }
        }
    }

    public partial class CustomDialogViewModel : ViewModelBase, IModalDialogViewModel, IDataErrorInfo
    {
        private string _name = string.Empty;
        private bool _isOkClicked;
        
        public string Name
        {
            get => _name;
            set 
            { 
                if (SetProperty(ref _name, value))
                {
                    OkCommand.NotifyCanExecuteChanged();
                }
            }
        }

        [RelayCommand(CanExecute = nameof(CanOk))]
        private void Ok()
        {
            _isOkClicked = true;
            DialogResult = true;
        }

        [RelayCommand]
        private void Cancel()
        {
            DialogResult = false;
        }

        private bool CanOk() => !string.IsNullOrWhiteSpace(Name);

        public bool? DialogResult { get; set; }

        #region IDataErrorInfo
        
        public string this[string columnName] => columnName == nameof(Name) && string.IsNullOrWhiteSpace(Name) 
            ? "Name is required" 
            : string.Empty;

        public string Error => string.Empty;
        
        #endregion
    }
}
